package models

import (
	"gorm.io/gorm"
	"log"
	"time"
	"ttsApp/internal/db"
)

type TTSJobRecord struct {
	gorm.Model
	Text     string `json:"text"`
	MD5      string `json:"md5"`
	Speed    int    `json:"speed"`
	Status   int    `json:"status"`
	Callback string `json:"callback"`
	Output   string `json:"output"`
	Duration int64  `json:"duration"`
}

func (r *TTSJobRecord) BeforeCreate(tx *gorm.DB) (err error) {
	return
}

func (r *TTSJobRecord) BeforeUpdate(tx *gorm.DB) (err error) {
	return
}

func (r *TTSJobRecord) BeforeDelete(tx *gorm.DB) (err error) {
	return
}

func AutoMigrate() {
	if err := db.DB.AutoMigrate(&TTSJobRecord{}); err != nil {
		log.Fatal(err)
	}
}
func GetRequestByMD5(md5 string) *TTSJobRecord {
	req := &TTSJobRecord{}
	_ = db.DB.Where("md5 = ? and status = ?", md5, 2).First(req).Error
	if len(req.Output) == 0 {
		return nil
	}

	return req
}

func InsertRequest(req *TTSJobRecord) error {
	return db.DB.Create(req).Error
}

func UpdateRequestStatus(id int64, status int, output string, duration int64) error {
	return db.DB.Model(&TTSJobRecord{}).Where("id = ?", id).Update("status", status).Update("output", output).Update("duration", duration).Error
}

func getTodayMidnight() time.Time {
	now := time.Now()
	midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	return midnight
}

func FindOldRecords() []TTSJobRecord {
	var records []TTSJobRecord
	midnight := getTodayMidnight()

	_ = db.DB.Model(&TTSJobRecord{}).Where("updated_at < ?", midnight).Find(&records).Error
	return records
}
func RemoveOldRecords() {
	midnight := getTodayMidnight()
	_ = db.DB.Where("updated_at < ?", midnight).Unscoped().Delete(&TTSJobRecord{}).Error
}
